package com.teamone.etl.systemsettings.aspect;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.teamone.etl.systemsettings.controller.UserformController;
import com.teamone.etl.systemsettings.entity.OperatingRecord;
import com.teamone.etl.systemsettings.entity.Userform;
import com.teamone.etl.systemsettings.service.OperatingRecordService;
import com.teamone.etl.systemsettings.utils.IpUtils;
import com.teamone.etl.systemsettings.utils.OperatingUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Method;
import java.util.Date;

/**
 @author WangZhuoRan */
@Aspect
@Configuration
public class OperatingRecordAspect {

    @Resource
    private HttpServletRequest request;

    @Resource
    private OperatingRecordService operatingRecordService;

    @Around("execution(* com.teamone.etl.systemsettings.controller.*.*(..)) " +
            "&& (@annotation(org.springframework.web.bind.annotation.GetMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PostMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.DeleteMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.PutMapping) " +
            "|| @annotation(org.springframework.web.bind.annotation.RequestMapping))")
    public Object adminControllerBeforeValidation(ProceedingJoinPoint joinPoint) throws Throwable {

        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        NoAspect noAspect = method.getAnnotation(NoAspect.class);
        //如果在方法上没有自定义注解--执行
        if(noAspect ==null){

            Userform attribute = (Userform) request.getSession().getAttribute(UserformController.ADMIN_ID);
            OperatingRecord operatingRecord = new OperatingRecord();
            operatingRecord.setUserId(attribute.getId());
            operatingRecord.setOperatingTime(new Date());
            operatingRecord.setUserIpAddress(IpUtils.getIp(request));
            //记录操作内容
            operatingRecord.setOperatingContext(OperatingUtils.operating(request,joinPoint));

            operatingRecordService.createOperatingRecord(operatingRecord);
        }

        return joinPoint.proceed();
    }

}
